<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, HasDateTimeFormatter;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::deleted(function ($user) {
            Oauth::query()->where("user_id",$user->id)->delete();
        });
    }


    /**
     * 微信小程序用户注册
     * @param string $openid
     * @param string $session_key
     * @param array $post
     * @return array
     */
    public static function weChatRegister(string $openid = '',string $session_key = '',array $post = []): array
    {
        $userInfo = $post['userInfo'];
        $user = new self;
        $user->name = uniqid();
        $user->nickname = $userInfo['nickName'];
        $user->avatar = $userInfo['avatarUrl'];
        $res = $user->save();
        if ($res){
            Oauth::addData($user->id,$openid,$user->nickname);
        }
        $token = $user->createToken('user_'.$user->name)->plainTextToken;
        return array_merge($user->toArray(),['token'=>$token,'session_key'=>$session_key]);
    }
}
